package de.lgohlke.format;

/**
 * <p>
 * UnitFormatter class.
 * </p>
 * 
 * @author lars
 * @version $Id: $
 */
public final class UnitFormatter
{
  private UnitFormatter()
  {
    // ok
  }

  private final static String[] units      = new String[] { "B", "KB", "MB", "GB", "TB", "PB" };
  private final static int      CONST_1024 = 1024;

  /**
   * http://stackoverflow.com/questions/3263892/format-file-size-as-mb-gb-etc
   * 
   * @param size
   *          a long.
   * @return a {@link java.lang.String} object.
   */
  public static String readableFileSize(final long size)
  {
    if (size <= 0)
    {
      return "0";
    }

    int digitGroups = (int) (Math.log10(size) / Math.log10(CONST_1024));

    return String.format("%.2f %s", size / Math.pow(CONST_1024, digitGroups), units[digitGroups]);
  }

  public static String readableFileSize(final double size)
  {
    return readableFileSize(new Double(size).longValue());
  }

}
